﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Mvc.Extensions;
using System.Web.Routing;
using MvcEngine.Core;
using MvcEngine.Core.Utils;
using MvcEngine.Core.Localization;

namespace MvcEngine.Mvc.Filters
{
    public class CaptchaFilter : ActionFilterAttribute
    {
        private string captchaName;

        public string CaptchaName
        {
            get { return captchaName; }
            set { captchaName = value; }
        }

        public CaptchaFilter()
        {

        }

        public CaptchaFilter(string captchaName)
        {
            this.captchaName = captchaName;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (string.IsNullOrEmpty(captchaName))
                captchaName = CaptchaConsts.DefaultName;

            string captchaValue = filterContext.HttpContext.Request.Form[captchaName];
            string captchaKey = filterContext.HttpContext.Request.Form[CaptchaConsts.KeyName];

            var modelState = filterContext.Controller.ViewData.ModelState;
            modelState.Remove(CaptchaConsts.KeyName);

            if (string.IsNullOrEmpty(captchaKey) || string.IsNullOrEmpty(captchaValue))
            {
                modelState.AddError(captchaName, ResourceReader.Current.GetString("CaptchaBadRequest"));
                return;
            }

            string cacheValue = CacheManager.Current.GetFromCache(captchaKey) as string;
            if (!string.IsNullOrEmpty(cacheValue))
            {
                if (cacheValue != captchaValue)
                {
                    modelState.AddError(captchaName, ResourceReader.Current.GetString("CaptchaInvalidData"));
                }
            }
            else
            {
                modelState.AddError(captchaName, ResourceReader.Current.GetString("CaptchaKeyIsExpired"));
            }
        }
    }
}
